<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>SafeSynchrome</title>
    <link rel="stylesheet" type="text/css" href="css/main.css" />
    <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="js/config.js"></script>
    <script type="text/javascript">

        var login_name = localStorage["ss_login_name"];
        var password = localStorage["ss_password"];
        var realm = localStorage["ss_realm"];
        var apikey = localStorage["ss_apikey"];
        var home_url = localStorage["ss_user_home"];
        var recycle_url = localStorage["ss_user_recyclebin"];
        var service_url = localStorage["ss_service_url"];
        var session_token;

        (function() {
            /* Get session token from cookie first */
            chrome.cookies.get({
                "url" : service_url,
                "name" : "auth"
            }, function(cookie) {
                if (cookie == null) {
                    $.get(service_url + "sessiontoken", {
                        "loginName" : login_name,
                        "password" : password,
                        "realm" : realm,
                        "service" : apikey
                    }, function (response) {
                        if (response.Status == RESPONSE_STATUS["ERROR"]) {
                            $("body").load("options.html");
                        } else {
                            session_token = response.sessiontoken;
                            chrome.cookies.set({
                                "url" : service_url,
                                "name" : "auth",
                                "value" : response.sessiontoken,
                                "domain" : ".safesync.com",
                                "path" : "/",
                                "expirationDate" : Math.floor((new Date().getTime() / 1000) + 86400 * 365),
                            });
                        }
                    });
                } else {
                    session_token = cookie.value;
                }
            });
            
            $("#search").live("submit", function(){search()});
        })();
        
        function home() {
            accessNode(service_url + "home");
        }
        
        function search() {
            var key = ".*";
            var result = [];
            
            $.each($("#key").val(), function(index, value) {
                key += value + ".*";
            });

            $("#filesroot").empty();
            $("#filesroot").append("<div class='files'><span class='content name'>Name</span><span class='content type'>Type</span><span class='content time'>Last Modified</span><span class='op'></span></div>");
            
            var regex = new RegExp(key, "i");
            searchNode(home_url, regex, result, 1);
        }
        
        function accessNode(node_url) {
            $.get(node_url, {
                "_auth" : session_token,
                "absUri" : 1
            }, function(container) {
                $("#filesroot").empty();

                if (container.parent != null) {
                    $(document.createElement('div')).text("Back to parent folder...").click(function() {
                        accessNode(container.parent);
                    }).hover(function() {
                        $(this).addClass('hover');
                    }, function() {
                        $(this).removeClass('hover');
                    }).appendTo("#filesroot");
                }

                /** TODO: next page */
                if (container.node.length != 0) {
                    $("#filesroot").append("<div class='files'><span class='content name'>Name</span><span class='content type'>Type</span><span class='content time'>Last Modified</span><span class='op'></span></div>");
                    $.each(container.node, function(nodeIndex, node) {
                        outputNode(nodeIndex, node);
                    });
                } else {
                    $("#filesroot").text("Empty!");
                }
            });
        }
        
        function searchNode(url, regex, result, page) {
            $.get(url, {
                "_auth" : session_token,
                "absUri" : 1,
                "page" : page
            }, function(container) {
                if (container.node.length != 0) {
                    $.each(container.node, function(nodeIndex, node) {
                        if (regex.test(node.name)) {
                            $("#error_msg").empty();
                            result.push(node);
                            outputNode(nodeIndex, node);
                        }
                        
                        if (node.container == 1) {
                            searchNode(node.uri, regex, result, 1);
                        }
                    });
                }
                
                if (container.pages > 1 && container.page == 1) {
                    for (var i = 2; i <= container.pages; i++) {
                        searchNode(url, regex, result, i);
                    }
                }
                
                if (result.length == 0) {
                    $("#error_msg").text("Not Found!");
                }
            });
        }
        
        function outputNode(nodeIndex, node) {
            var new_node = document.createElement('div')
            $(new_node).attr('id', node.id).attr('link', node.uri).addClass('files').appendTo("#filesroot")/*.mouseover(function() {
                $("#status").text($(this).attr('link'));
            }).mouseout(function() {
                $("#status").empty();
            })*/;
                
            $(document.createElement('span')).addClass('content').addClass("name").text(node.name).appendTo(new_node);
            $(document.createElement('span')).addClass('content').addClass("type").text(node.desc).appendTo(new_node);
            $(document.createElement('span')).addClass('content').addClass("time").text(node.displayModified).appendTo(new_node);
            $(document.createElement('span')).addClass('op').append($(document.createElement('a')).attr('href', '#').text("[Share]")).appendTo(new_node);
            
            if (node.container == 1) {
                $(new_node).children(".content").click(function() {
                    accessNode(node.uri);
                }).hover(function() {
                    $(this).parent().addClass('hover');
                }, function() {
                    $(this).parent().removeClass('hover');
                });
            }
        }
    </script>
</head>
<body id="popup">
    <center>
        <form id="search" onsubmit="return false">
            <button onclick="home();">Get Home</button>&nbsp;or&nbsp;
            Search: <input type="text" id="key" name="key" />
        </form>
        <div id="error_msg" class="error"></div>
        <div id='filesroot'>
            <div class='files'><span class='content name'>Name</span><span class='content type'>Type</span><span class='content time'>Last Modified</span><span class='op'></span></div>
        </div>
        <div id="status" class="status"></div>
    </center>
</body>
</html>